from celery import shared_task
from django.conf import settings
from django.utils import timezone
from iClouds.fsGradeSDK import aniPortraitServer as ATV
from PIL import Image
from mysqldb.models import AllinpayUploadList
import logging

logger = logging.getLogger(__name__)


@shared_task
def Test(*args, **kwargs):
    """测试"""
    return {"rescode": 200, "resmsg": "HelloWorld"}


# @shared_task
# def requestCode(*args, **kwargs):
#     """请求code"""
#     state = "tb9"
#     wxSDK = WX.wxChatRequest()
#     url = f"/connect/oauth2/authorize?appid={WX.APPID}&redirect_uri={urlencode(WX.RECT)}&response_type=code&scope=snsapi_base&state={state}#wechat_redirect"

#     return {"rescode": 200, "resmsg": "HelloWorld"}


@shared_task
def taskGetServer():
    """获取服务器信息"""
    r = ATV()
    res = {"host": r.gradio_host, "port": r.gradio_port, "web": r.gradio_web}
    r.stop()
    return res


@shared_task
def taskListModels():
    """查询模板列表"""
    r = ATV()
    res = r.listModels()
    r.stop()
    return res


@shared_task
def taskPostAniPortrait(*args, **kwargs):
    """创建动画"""
    # logger.info(f"[aniPortanit] [completed] {args}")
    if not len(args):
        return {"status": "FAILURE", "result": "用户身份验证失败"}

    r = ATV()
    host, port, web = r.gradio_host, r.gradio_port, r.gradio_web
    # res = r.postVideo(**kwargs)
    # r.stop()
    res = r.postVideo2(**kwargs)
    if not res or res["rescode"]:
        return {"status": "FAILURE", "result": "创建动画失败"}

    db = AllinpayUploadList(
        answer=args[0],
        sorth="名画也疯狂",
        # header=f'{host}:{web}{res[0]["video"].replace("../models/output/","/media/output/")}',
        header=f'{host}:{web}{res["video"].replace("../models/output/","/media/output/")}'[
            :-4
        ]
        + "mp4",
        filename=f'{host}:{web}/media/models/{res["cover"]}',
        creattime=timezone.now(),
    )
    db.save()

    # logger.info(f"[aniPortanit] [completed] {res}")
    # logger.info(f"[aniPortanit] [completed] {type(res[1])}")
    return res
